import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

public class Server {

	public Server(Properties prop){
		
		//The Work Queue
		ArrayBlockingQueue<Point> latestPoint = new ArrayBlockingQueue<Point>(1);
		AtomicBoolean continueWork = new AtomicBoolean(true);
				
		//The View, Model, and Controller
		View theView = new View(prop);
		Controller theCont = new Controller(theView, prop, latestPoint, continueWork);
		RenderMachine theMachine = new RenderMachine(prop, theCont, continueWork, latestPoint);	
		
		
		//Start the machine!
		if(prop.getProperty("verbose").equals("true")){
			System.out.println("Starting Machine...");
		}
		Thread machineThread = new Thread(theMachine);
		machineThread.start();
		theView.setVisible(true);		
		try {
			machineThread.join();
		} catch (InterruptedException e) {
			
		}
	}
	
	
	public static void main(String[] args) {
		
		//First, process the arguments
		Properties theProps = new Properties();
		boolean continuePlease = ArgumentProcessor.process(theProps, args);
		if(continuePlease == false){
			System.exit(0);
		}		
		
		if(theProps.getProperty("verbose").equals("true")){
			System.out.println("Buddhabrot Server");
			System.out.println("Verbose Mode: Engaged");
			System.out.println(theProps);
		}
		
		int width;
		int height;
		boolean fullscreen = Boolean.parseBoolean(theProps.getProperty("fullscreen"));
		boolean verbose = Boolean.parseBoolean(theProps.getProperty("verbose"));
		
		if(fullscreen){
			Toolkit toolkit =  Toolkit.getDefaultToolkit ();
	        Dimension dim = toolkit.getScreenSize();
			height = dim.height; 	  
			width = dim.width;
		}
		else{
			width = Integer.parseInt(theProps.getProperty("width"));
			height = Integer.parseInt(theProps.getProperty("height"));
		}
		
		int row = Integer.parseInt(theProps.getProperty("row"));
		int column = Integer.parseInt(theProps.getProperty("column"));
		
		//initialize the boxes
		int boxWidth = width/column;
		int lastBoxWidth = boxWidth + (width - boxWidth*column);
		int boxHeight = height/row;
		int lastBoxHeight = boxHeight + (height - boxHeight*row);
		
		if(verbose) System.out.print("boxWidth = " + boxWidth);
		if(verbose) System.out.print(" lastBoxWidth = " + lastBoxWidth);
		if(verbose) System.out.print(" boxHeight = " + boxHeight);
		if(verbose) System.out.println(" lastBoxHeight = " + lastBoxHeight);
		
		theProps.setProperty("boxWidth", new Integer(boxWidth).toString());
		theProps.setProperty("lastBoxWidth", new Integer(lastBoxWidth).toString());
		theProps.setProperty("boxHeight", new Integer(boxHeight).toString());
		theProps.setProperty("lastBoxHeight", new Integer(lastBoxHeight).toString());
		
		new Server(theProps);
			
	}

}
